package com.qusouquan.android;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


public class MainActivity extends AppCompatActivity {


    WebView webView;
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Objects.requireNonNull(getSupportActionBar()).hide();
        //registerClipEvents();
        setContentView(R.layout.activity_main);
        webView=findViewById(R.id.web_view);//绑定ID
        WebSettings webSettings = webView.getSettings();
        //webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //webView.setWebViewClient(new WebViewClient());
        String url = "https://souquan.liuzou.com/index.php?r=index/wap&from=android";
        webView.loadUrl(url);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                //view.loadUrl("javascript: var allLinks = document.getElementsByTagName('a'); if (allLinks) {var i;for (i=0; i<allLinks.length; i++) {var link = allLinks[i];var target = link.getAttribute('target'); if (target && target == '_blank') {link.setAttribute('target','_self');link.href = 'newtab:'+link.href;}}}");
            }
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                Log.d(MainActivity.TAG,"url:" + url +"\n");
                if (isAppInstalled(webView.getContext(), "com.taobao.taobao") && (url.contains("taobao.com") || url.contains("tmall.com"))) {

                    /**
                     * && url.startsWith("taobao://")
                     *                         || url.startsWith("tbopen://")
                     */
                    //Objects.requireNonNull(getSupportActionBar()).show();
                    try{
                        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ONLY);
                        String newUrl = url.replace("https:", "taobao:");
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri uri = Uri.parse(newUrl);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setData(uri);
                        startActivity(intent);
                    }catch (Exception e){
                        return super.shouldOverrideUrlLoading(webView, url);
                    }
                    return true;
                } else {
                    return super.shouldOverrideUrlLoading(webView, url);
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean isAppInstalled(Context context, String uri) {
        PackageManager pm = context.getPackageManager();
        boolean installed;
        try {
            pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }

    private void registerClipEvents() {
        final ClipboardManager manager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        assert manager != null;
        manager.addPrimaryClipChangedListener(new ClipboardManager.OnPrimaryClipChangedListener() {
            @Override
            public void onPrimaryClipChanged() {
                if (manager.hasPrimaryClip() && manager.getPrimaryClip().getItemCount() > 0) {
                    CharSequence addedText = manager.getPrimaryClip().getItemAt(0).getText();
                    if (addedText != null) {
                        showDialog(addedText.toString());
                    }
                }
            }
        });
    }

    private void showDialog(String text){
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("淘口令");
        builder.setMessage(text);
        builder.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {

                    }
                });
        AlertDialog dialog=builder.create();
        dialog.show();
    }
}
